<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <style>
        *{ margin: 0; padding: 0; }
        #div2{ background: red; width: 100px; height: 100px; position: absolute; touch-action: none; }
    </style>
    <title>PC端与移动端滑动</title>
</head>
<body>
    <div id="div2"></div>

    <script>
        var flag = false;
        var cur = {
            x:0,
            y:0
        }
        var nx,ny,dx,dy,x,y ;
        function down(){
            flag = true;
            var touch ;
            if(event.touches){
                touch = event.touches[0];
            }else {
                touch = event;
            }
            cur.x = touch.clientX;
            cur.y = touch.clientY;
            dx = div2.offsetLeft;
            dy = div2.offsetTop;
        }
        function move(){
            if(flag){
                var touch ;
                if(event.touches){
                    touch = event.touches[0];
                }else {
                    touch = event;
                }
                nx = touch.clientX - cur.x;
                ny = touch.clientY - cur.y;
                x = dx+nx;
                y = dy+ny;
                div2.style.left = x+"px";
                div2.style.top = y +"px";
                //阻止页面的滑动默认事件
                document.addEventListener("touchmove",function(e){
                    e.preventDefault();
                    
                },false);
            }
            console.log(flag);
        }
        //鼠标释放时候的函数
        function end(){
            flag = false;
        }
        var div2 = document.getElementById("div2");
        div2.addEventListener("mousedown",function(){
            down();
        },false);
        div2.addEventListener("touchstart",function(){
            down();
        },false)
        div2.addEventListener("mousemove",function(){
            move();
        },false);
        div2.addEventListener("touchmove",function(){
            move();
        },false)
        document.body.addEventListener("mouseup",function(){
            end();
        },false);
        div2.addEventListener("touchend",function(){
            end();
        },false);
    </script>
</body>
</html>